package com.msb.api.filter.impl;

import com.msb.api.feign.BeaconCacheClient;
import com.msb.api.filter.CheckFilter;
import com.msb.common.constart.ApiConstant;
import com.msb.common.constart.CacheConstant;
import com.msb.common.enums.ExceptionEnums;
import com.msb.common.exception.GraceException;
import com.msb.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author: lmf
 * @Create: 2025/3/7 9:09
 * Description: 签名校验
 */
@Service("sign")
@Slf4j
public class SignCheckFilter implements CheckFilter {
    @Resource
    private BeaconCacheClient cacheClient;

    @Override
    public void check(StandardSubmit submit) {
        log.info("签名校验-SignCheckFilter");

        String text = submit.getText();
        String SIGN_INFO = "signInfo";

        // 判断短信内容是否有签名信息
        if (!text.startsWith(ApiConstant.SIGN_PREFIX) || !text.contains(ApiConstant.SIGN_SUFFIX)) {
            GraceException.display(ExceptionEnums.ERROR_SIGN);
        }
        // 获取短信签名
        String sign = text.substring(ApiConstant.SIGN_PREFIX.length(), text.indexOf(ApiConstant.SIGN_SUFFIX));

        if (StringUtils.isEmpty(sign)) {
            GraceException.display(ExceptionEnums.ERROR_SIGN);
        }

        // 获取redis中客户的签名信息
        Set<Map<String, Object>> signClient = cacheClient.sMembers(CacheConstant.CLIENT_SIGN + submit.getClientId());
        if (signClient == null || signClient.isEmpty()) {
            GraceException.display(ExceptionEnums.ERROR_SIGN);
        }

        for (Map<String, Object> map : signClient) {
            if (sign.equals(map.get(SIGN_INFO))) {
                // 设置签名信息
                submit.setSign(sign);
                submit.setSignId(Long.parseLong(map.get("id") + ""));
                log.info("【通过签名】验证后的信息：{}", submit);
                return;
            }
        }
        GraceException.display(ExceptionEnums.ERROR_SIGN);
    }
}
